import React, {Component} from "react";
import {Table, Space, Input, InputNumber, Button, Modal, Typography, message, Tooltip, Upload} from "antd";
import {API_URL} from "../constants";
import IntegratedComponent from "./IntegratedComponent";
import ImageUpload from "./ImageUpload";
import {
    convertKey,
    doubleIfNull,
    getCrmFields,
    getCrmProductsByParam,
    getCrmRecordFromSql, intIfNull,
    isBlank,
    strIfNull
} from "../util/util";
import {SearchOutlined} from '@ant-design/icons';
import * as XLSX from 'xlsx';

const {Text, Link} = Typography;

const {TextArea} = Input;

const ZOHO = window.ZOHO;

class QuoteTable extends Component {
    constructor(props) {
        super(props);

        this.state = {
            data: [],
            columns: [],
            moduleName: this.props.moduleName,
            scrollWidth: 0,
            screenHeight: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
            initObj: {},
            selectedRowKeys: [],
            // 存放子组件的字段和数据登信息，避免每次渲染子组件重复调用接口
            integratedObj: {},
            shouldTriggerOnChange: true,
            loading: false,
            modalVisible: false,
            productData: [],
            productColumns: [],
            selectedProductRowKeys: [],
            jsonName: this.props.jsonName,
            paste: this.props.paste === undefined,
            parentModuleName: this.props.parentModuleName,
            searchInput: {},
            productAllColumns: [],
            template: this.props?.template,
            formula: {}
        }

    }

    async componentDidMount() {
        this.setState({loading: true}, this.initFields);
    }


    async initFields() {
        const {moduleName, integratedObj, jsonName, parentModuleName} = this.state;
        let columns = [];
        let fields = await getCrmFields(moduleName);
        let obj = {};
        let mergedObj = [];
        let productData = [];
        let productColumns = []
        let conf = {};
        let formula = {};
        let productAllColumns = {};
        if (jsonName !== undefined) {
            const response = await fetch('./conf/' + jsonName);
            conf = await response.json()
            conf = conf.table;
        }
        let lookupmodulename = [];
        let scrollWidth = 0;

        for (const field of fields) {
            if (!field.view_type.create || field.data_type === 'ownerlookup') {
                continue;
            }
            if (field.data_type === "text") {
                obj[field.api_name] = "";
            }
            if (field.data_type === "lookup") {
                obj[field.api_name] = null;
                if (!lookupmodulename.includes(field.lookup.module.api_name)) {
                    mergedObj = [...mergedObj, await this.getView(field.lookup.module.api_name)];
                }
                lookupmodulename.push(field.lookup.module.api_name);

            }

            if (field.data_type === "imageupload") {
                obj[field.api_name] = [];
            }
            if (field.data_type === "double") {
                obj[field.api_name] = 0.0000;
            }

            if (field.data_type === "integer") {
                obj[field.api_name] = 0;
            }
            let hidden = false
            field.sum = false
            if (conf[field.api_name] !== undefined) {
                hidden = conf[field.api_name].hidden;
                field.read_only = conf[field.api_name].readOnly;
                if (!isBlank(conf[field.api_name].formula)) {
                    field.type = field.data_type
                    field.data_type = "formula";
                    field.formula = conf[field.api_name].formula;
                    formula[field.api_name] = {
                        type: conf[field.api_name].dataType,
                        formula: conf[field.api_name].formula
                    };
                }
                if (conf[field.api_name].sum === true) {
                    field.sum = true
                }
            }
            let column = {
                title: field.field_label,
                dataIndex: field.api_name,
                key: field.api_name,
                type: field.data_type,
                className: hidden ? 'hidden-column' : "",
                sum: field.sum,
                fixed: !isBlank(conf[field.api_name]?.fixed),
                width: conf[field.api_name]?.width,
                lookupModuleName: field.data_type === "lookup" ? field.lookup.module.api_name : "",
                formula: isBlank(conf[field.api_name]?.formula) ? "" : {
                    type: field.type,
                    formula: conf[field.api_name].formula
                },
                render: (text, record, index) => this.renderCell(field, text, record, index)
            }
            if (!hidden) {
                scrollWidth += isBlank(conf[field.api_name]?.width) ? 200 : intIfNull(conf[field.api_name]?.width);
            }
            columns.push(column)
        }
        console.log(columns)

        obj["id"] = "";
        mergedObj.forEach(tables => {
            let table = tables["Products"];
            if (table !== undefined) {
                productAllColumns = table.fields;
                productColumns = table.columns;
                productData = table.data;
            }
        })
        let dataSource = [];
        if (window.id !== undefined) {
            let req_data = {
                parameters: {},
                method: "GET",
                url: API_URL + `/crm/v3/${moduleName}/search?criteria=(${parentModuleName}.id:equals:${window.id})`,
                param_type: 1,
            };
            const dataIndexArray = columns.map(item => item.dataIndex);
            dataIndexArray.push("id");
            let rate = this.props.getRate();
            await ZOHO.CRM.CONNECTION.invoke("crm", req_data).then((data) => {
                let detail = data.details.statusMessage.data;
                dataSource = detail?.map(item => {
                    item.rate = rate;
                    return dataIndexArray.reduce((obj, dataIndex, currentIndex) => {
                        if (dataIndex === "Picture") {
                            item[dataIndex]?.map((a, index) => {
                                item[dataIndex][index].Description = "";
                            })
                        }
                        obj[dataIndex] = item[dataIndex];
                        if (dataIndex === "Name") {
                            obj["key"] = item[dataIndex] ? item[dataIndex] : currentIndex
                        }
                        return obj;
                    }, {});
                });
                dataSource.sort((a, b) => {
                    if (intIfNull(a.Name) < intIfNull(b.Name)) {
                        return -1;
                    }
                    if (intIfNull(a.Name) > intIfNull(b.Name)) {
                        return 1;
                    }
                    return 0;
                });
            });
        }
        console.log(JSON.stringify(formula))
        this.setState({
            columns: columns,
            scrollWidth: scrollWidth,
            initObj: obj,
            data: dataSource === undefined ? [] : dataSource,
            loading: false,
            integratedObj: mergedObj,
            productColumns: productColumns,
            productData: productData,
            productAllColumns: productAllColumns,
            formula: formula,
        });

    }

    getView = async (moduleName) => {
        const getColumnSearchProps = this.getColumnSearchProps;
        let crmFields = await getCrmFields(moduleName);
        let idMap = new Map();
        let fields = [];
        let types = {};
        crmFields.map(item => {
            idMap.set(item.id, item.field_label)
            fields.push(item.api_name)
            types[item.id] = item.data_type;
        })
        let columns = [];
        let dataSource = [];
        let options = [];

        await ZOHO.CRM.META.getCustomViews({"Entity": moduleName}).then(async function (data) {
            let defaultid = data.info.default
            let req_data = {
                parameters: {},
                method: "GET",
                url: API_URL + `/crm/v5/settings/custom_views/${defaultid}?module=${moduleName}`,
                param_type: 1,
            };
            await ZOHO.CRM.CONNECTION.invoke("crm", req_data).then((data) => {
                data.details.statusMessage.custom_views[0].fields.map(field => {
                    let column = {
                        title: idMap.get(field.id),
                        dataIndex: field.api_name,
                        key: field.api_name,
                        width: 200,
                        type: types[field.id],
                        filterSearch: true,
                        ...getColumnSearchProps(field.api_name),
                    }
                    columns.push(column)
                })
            });
            req_data = {
                parameters: {},
                method: "GET",
                url: API_URL + `/crm/v4/${moduleName}?fields=${fields}`,
                param_type: 1,
            };
            await ZOHO.CRM.CONNECTION.invoke("crm", req_data).then((data) => {
                dataSource = data.details.statusMessage.data;
                dataSource?.map(item => {
                    item.key = item.id
                });
                options = dataSource?.map(item => ({
                    value: item.id,
                    label: item.Name ? item.Name : item.Product_Name,
                }));
            });
        });
        const scrollWidth = columns.length;
        let integratedObj = {
            columns: columns,
            scrollWidth: scrollWidth,
            data: dataSource,
            options: options,
            fields: fields,
        };
        let load = {};
        load[moduleName] = integratedObj;
        return load;
    }

    renderCell = (field, text, record, index) => {
        const {paste} = this.state;
        let editable = !field.read_only;
        let data_type = field.data_type;
        let children = null;

        if (editable) {
            if (data_type === "text") {
                paste ?
                    children =
                        <Tooltip title={record[field.api_name]}>
                            <Input
                                onPaste={(e) => this.handlePaste(e, field, index)}
                                value={record[field.api_name]}
                                onClick={this.inputClick}
                                onChange={(e) => this.handleCellChange(e.target.value, field, index)}
                            /> </Tooltip>
                    : children = <Tooltip title={record[field.api_name]}>
                        <Input
                            onClick={this.inputClick}
                            value={record[field.api_name]}
                            onChange={(e) => this.handleCellChange(e.target.value, field, index)}
                        /></Tooltip>;
            }

            if (data_type === "lookup") {
                if (record === null || record === undefined) {
                    editable = false;
                } else {
                    let value = record[field.api_name];
                    const {integratedObj} = this.state;
                    let key = record['Product'];
                    children = <IntegratedComponent
                        tableProps={integratedObj}
                        key={key?.id}
                        onLoadIntegratedObj={this.onLoadIntegratedObj}
                        moduleName={field.lookup.module.api_name}
                        value={value}
                        apiName={field.api_name}
                        onChange={(e) => this.handleCellChange(e, field, index)}
                    />;
                }
            }


            if (data_type === "imageupload") {
                if (record === null || record === undefined) {
                    editable = false;
                } else {
                    let picture = undefined
                    if (record.Picture !== null) {
                        picture = record.Picture[0]
                    }
                    children = <ImageUpload
                        id={record.id} picture={picture}
                        onChange={(e) => this.handleCellChange(e, field, index)}
                    />

                }
            }
            if (data_type === "double") {
                children = <InputNumber
                    step={0.0001}
                    onClick={this.inputClick}
                    value={record[field.api_name]}
                    onChange={(e) => this.handleCellChange(e, field, index)}
                />;
            }

            if (data_type === "integer") {
                children = <InputNumber
                    step={1}
                    onClick={this.inputClick}
                    value={record[field.api_name]}
                    onChange={(e) => this.handleCellChange(e, field, index)}
                />;
            }
            if (data_type === "textarea") {
                children = <TextArea
                    value={record[field.api_name]}
                    onChange={(e) => this.handleCellChange(e.target.value, field, index)}
                />
            }

            if (data_type === "formula") {
                let step = 0.0001;
                let digit = 4;
                if (field.type === "int") {
                    step = 1;
                    digit = 0;
                }
                const replacedFormula = field.formula.replace(/\[(.*?)\]/g, (match, fieldName) => record[fieldName]);
                let result = 0;
                try {

                    // 使用 eval() 计算表达式
                    result = eval(replacedFormula);
                    // 检查计算结果是否为有限数值
                    if (!Number.isFinite(result)) {
                        result = 0;
                    }
                    result = Number(result.toFixed(digit))

                } catch (error) {
                    console.error(`计算公式出错：${error}`);
                }
                children = <InputNumber
                    step={step}
                    value={result}
                    onBlur={(e) => this.handleCellChange(e, field, index)}
                />;
            }

        }
        return editable ? children : record[field.api_name];
    };

    inputClick = (event) => {
        // e.select();
        console.log(222, event.target.select())
    }
    onLoadIntegratedObj = (newIntegratedObj) => {
        const {integratedObj} = this.state;

    }

    handleCellChange = async (newValue, field, index) => {

        const {data, shouldTriggerOnChange, formula} = this.state;
        if (!shouldTriggerOnChange) {
            this.setState({
                shouldTriggerOnChange: true,
            });
            return;
        }
        const newData = [...data];
        if (field.data_type === "text" || field.data_type === "textarea") {
            newData[index][field.api_name] = strIfNull(newValue);
        }

        if (field.data_type === "double" || field.data_type === "integer") {
            newData[index][field.api_name] = doubleIfNull(newValue);

        }
        if (field.data_type === "integer" || field.data_type === "formula") {
            newData[index][field.api_name] = intIfNull(newValue);
        }
        Object.keys(formula).forEach(key => {
            let a = formula[key].formula;
            if (a.includes(field.api_name)) {
                let digit = 4;
                if (field.type === "int") {
                    digit = 0;
                }
                const replacedFormula = a.replace(/\[(.*?)\]/g, (match, fieldName) => newData[index][fieldName]);
                let result = 0;
                try {

                    // 使用 eval() 计算表达式
                    result = eval(replacedFormula);
                    // 检查计算结果是否为有限数值
                    if (!Number.isFinite(result)) {
                        result = 0;
                    }
                    result = Number(result.toFixed(digit))
                    newData[index][key] = result;
                } catch (error) {
                    console.error(`计算公式出错：${error}`);
                    newData[index][key] = 0;
                }
            }
        })


        if (field.data_type === "lookup") {
            if (field.api_name === 'Product' && !isBlank(newValue.value)) {
                await ZOHO.CRM.API.getRecord({
                    Entity: "Products", approved: "both", RecordID: newValue.value
                }).then(function (data) {
                    let temp = newData[index];
                    let product = data.data[0];
                    Object.keys(product).forEach(key => {
                        if (temp.hasOwnProperty(key) && key !== "id") {
                            newData[index][key] = product[key];
                        }
                    });

                })
            }
            newData[index][field.api_name] = {
                id: newValue.value,
                name: newValue.label
            }
        }
        if (field.data_type === "imageupload") {
            debugger
            if (newData[index][field.api_name]?.length > 0) {
                if (newValue.desc === 'add') {
                    delete newValue.desc;
                    newData[index][field.api_name][0] = newValue;
                }
                if (newValue.desc === 'delete') {
                    if (newData[index][field.api_name] !== null) {
                        if (newData[index][field.api_name][0].id === undefined) {

                            newData[index][field.api_name] = null
                        } else {
                            newData[index][field.api_name][0] = {
                                id: newData[index][field.api_name][0].id,
                                _delete: null
                            }
                        }
                    }
                }
            } else {
                delete newValue.desc;
                if (newData[index][field.api_name] === null) {
                    newData[index][field.api_name] = [newValue];
                } else {
                    newData[index][field.api_name] = [newValue];
                }
            }
        }
        this.setState({
            data: newData,
        });

    };
    handlePaste = (e, field, index) => {
        const {data, columns, initObj} = this.state;
        let newData = [...data];
        const clipboardData = e.clipboardData || window.clipboardData;
        let pastedText = clipboardData.getData('text');
        let rows = [];
        if (pastedText.endsWith("\n")) {
            pastedText = pastedText.slice(0, -1);
            rows = pastedText.split("\n");
        }
        if (pastedText.endsWith("\r\n")) {
            pastedText = pastedText.slice(0, -2);
            rows = pastedText.split("\r\n");
        }
        let textcolumns = columns.filter(column => column.type === "text");
        let apinames = [];
        let flag = false;
        textcolumns.forEach(textcolumn => {
            if (field.api_name === textcolumn.dataIndex) {
                flag = true;
            }
            if (flag) {
                apinames.push(textcolumn.dataIndex);
            }
        })
        let rate = this.props.getRate();
        rows.forEach((row, i) => {
            let datas = row.split("\t");
            if (newData[index + i] === undefined) {
                const newobj = {...initObj};
                newobj.key = (newData.length + 1);
                newobj.Name = ((newData.length + 1)) + "";
                newobj.rate = rate
                newData = [...newData, newobj];
            }
            datas.forEach((data, j) => {
                let apiname = apinames[j];
                newData[index + i][apiname] = data
            })
        })
        this.setState({
            data: newData,
            shouldTriggerOnChange: false
        });
    }
    addRow = () => {
        let rate = this.props.getRate();
        const {initObj, data} = this.state;
        const newobj = {...initObj};
        newobj.key = (data.length + 1);
        newobj.Name = ((data.length + 1)) + "";
        newobj.rate = rate;
        const newData = [...data, newobj]; // 创建一个新的数组，将 initObj 添加到末尾
        this.setState({data: newData});
    }
    removeRow = (index) => {
        const {data, selectedRowKeys} = this.state;

        const newData = data.filter(item => !selectedRowKeys.includes(item.key)); // 创建一个新的数组，复制原始数据
        // 重新设置name行号
        const newDataWithContinuousName = newData.map((item, index) => ({
            ...item,
            Name: strIfNull(index + 1),
            key: index + 1,
        }));
        this.setState({data: newDataWithContinuousName, selectedRowKeys: []});
    }
    onSelectChange = (newselectedRowKeys) => {
        this.setState({selectedRowKeys: newselectedRowKeys});
    };
    onProductSelectChange = (newselectedRowKeys) => {
        this.setState({selectedProductRowKeys: newselectedRowKeys});
    };
    handleOpenModal = () => {
        this.setState({modalVisible: true});
    };

    handleCloseModal = () => {
        this.setState({modalVisible: false});
    };

    handleOkModal = () => {
        const {productData, selectedProductRowKeys, data, initObj} = this.state;
        const newData = [...data];
        const selectProductData = productData.filter(item => {
            let product = newData.find(a => a.Product?.id === item.key);
            if (product !== undefined) {
                return false;
            }
            return selectedProductRowKeys.includes(item.key)
        }); // 创建一个新的数组，复制原始数据
        let rate = this.props.getRate();
        selectProductData.map((item, index) => {
            const newobj = {...initObj};
            newobj.key = (data.length + index + 1);
            newobj.Name = ((data.length + index + 1)) + "";
            newobj.Product = {
                id: item.key,
                name: item.product_Name === undefined ? item.Product_Name : item.product_Name
            }
            newobj.rate = rate;
            Object.keys(item).forEach(key => {
                if (newobj.hasOwnProperty(key) && key !== "id") {
                    newobj[key] = item[key];
                }
            });
            newData.push(newobj)
        })

        this.setState({data: newData});
        message.success("保存成功")
    };
    handleSearch = (selectedKeys, confirm, dataIndex) => {
        const {searchInput, productColumns} = this.state;
        searchInput[dataIndex] = selectedKeys[0];
        const dataIndexArray = [];
        const typeArray = {};
        productColumns.map(item => {
            dataIndexArray.push(item.dataIndex)
            typeArray[item.dataIndex] = item.type
        });
        getCrmProductsByParam(dataIndexArray, typeArray, searchInput).then((data) => {
            data?.map(item => {
                item.key = item.id
            });
            this.setState({
                productData: data,
                searchInput: searchInput,
            })
        })
        confirm();
    };
    handleReset = (clearFilters, dataIndex) => {
        const {searchInput} = this.state;
        searchInput[dataIndex] = "";
        this.setState({
            searchInput: searchInput,
        })
        clearFilters();
    };

    getColumnSearchProps = (dataIndex) => ({
        filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters, close}) => (
            <div
                style={{
                    padding: 8,
                }}
                onKeyDown={(e) => e.stopPropagation()}
            >
                <Input
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{
                        marginBottom: 8,
                        display: 'block',
                    }}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                        icon={<SearchOutlined/>}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        搜索
                    </Button>
                    <Button
                        onClick={() => clearFilters && this.handleReset(clearFilters, dataIndex)}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        重置
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => {
                            close();
                        }}
                    >
                        关闭
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: (filtered) => (
            <SearchOutlined
                style={{
                    color: filtered ? '#1677ff' : undefined,
                }}
            />
        ),
        onFilterDropdownOpenChange: (visible) => {
            if (visible) {

            }
        },

        render: (text) =>
            text
    });

    importFile = (file, fileList) => {
        let reader = new FileReader();
        const {columns, productAllColumns, initObj, integratedObj, template} = this.state
        console.log(integratedObj)
        this.setState({loading: true})
        reader.onload = async (ev) => {
            try {
                var data = ev.target.result

                var workbook = XLSX.read(data, {
                    type: 'binary'
                }) // 以二进制流方式读取得到整份excel表格对象
                var persons = []; // 存储获取到的数据
            } catch (e) {
                console.log(e);
                console.log('文件类型不正确');
                return;
            }
            // 表格的表格范围，可用于判断表头是否数量是否正确
            var fromTo = '';
            // 遍历每张表读取
            for (var sheet in workbook.Sheets) {
                if (workbook.Sheets.hasOwnProperty(sheet)) {
                    fromTo = workbook.Sheets[sheet]['!ref'];

                    persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet], {defval: ""}));
                    break; // 如果只取第一张表，就取消注释这行
                }
            }
            let keyMap = {};
            let typeMap = {};
            columns.forEach(column => {
                keyMap[column.title] = column.dataIndex
                typeMap[column.dataIndex] = {
                    type: column.type,
                    lookupModuleName: column.lookupModuleName,
                    formula: column.formula,
                }
            })

            console.log(keyMap)
            //在控制台打印出来表格中的数据
            let resultData = convertKey(persons, keyMap)
            console.log(resultData);
            try {
                let productBatches = [];
                let products = [];
                resultData.forEach(item => {
                    products.push("'" + item.Product + "'")
                    if (products.length === 50) {
                        productBatches.push(products)
                        products = [];
                    }
                })
                if (products.length > 0) {
                    productBatches.push(products)
                }
                let productMap = {}
                if (productBatches.length > 0) {
                    for (const batch of productBatches) {
                        const result = await getCrmRecordFromSql(`select ${productAllColumns} from Products where Product_Name in (${batch})`);
                        if (!isBlank(result)) {
                            result.forEach(item => {
                                productMap[item.Product_Name] = item;
                            });
                        }
                    }
                }
                const newData = [];
                console.log(typeMap)
                let emptyProduct = [];
                // 先获取基本数据
                resultData.forEach((item, index) => {
                    let product = productMap[item.Product];
                    const newobj = {...initObj};
                    newobj.key = (index + 1);
                    newobj.Name = ((index + 1)) + "";
                    newobj.rate = this.props.getRate()
                    if (!isBlank(product)) {
                        newobj.Product = {
                            id: product.id,
                            name: product.Product_Name
                        }
                    }
                    // 除报价外，都需要导入产品
                    if (template !== "quoteTemplate" && isBlank(product)) {
                        emptyProduct.push(item.Product)
                        return;
                    }
                    Object.keys(newobj).forEach(key => {
                        if (key === "id" || key === "Product" || key === "key") {
                            return;
                        }
                        if (!item.hasOwnProperty(key)) {
                            return;
                        }
                        let value;
                        switch (typeMap[key].type) {
                            case "text":
                                value = strIfNull(item[key])
                                break
                            case "lookup":
                                let optionMap = {};
                                integratedObj.forEach(tables => {
                                    let table = tables[typeMap[key].lookupModuleName];
                                    if (table !== undefined) {
                                        let options = table.options
                                        options.map(item => {
                                            optionMap[item.label] = item.value
                                        })
                                    }
                                })
                                if (!isBlank(optionMap[item[key]])) {
                                    value = {
                                        id: optionMap[item[key]],
                                        name: item[key]
                                    }
                                } else {
                                    value = null
                                }
                                break
                            case "double":
                                value = doubleIfNull(item[key])
                                break
                            case "integer":
                                value = intIfNull(item[key])
                                break
                        }
                        // 报价以excel中的值为主可以覆盖产品带入的值，其他以产品带入为主不能覆盖
                        if (template === "quoteTemplate") {
                            if (!isBlank(product)) {
                                if (product.hasOwnProperty(key)) {
                                    newobj[key] = isBlank(item[key]) ? isBlank(product[key]) ? newobj[key] : product[key] : isBlank(item[key]) ? newobj[key] : value;
                                    return;
                                }
                            }
                        } else {
                            if (product.hasOwnProperty(key)) {
                                newobj[key] = isBlank(product[key]) ? newobj[key] : product[key];
                                return;
                            }
                        }
                        newobj[key] = isBlank(item[key]) ? newobj[key] : value;
                    });

                    newData.push(newobj)
                })
                if (emptyProduct.length > 0) {
                    message.error(`以下产品${emptyProduct}不存在`)
                }
                // 二次循环计算公式字段
                newData.forEach(item => {
                    Object.keys(item).forEach(key => {
                        if (isBlank(typeMap[key]?.formula)) {
                            return;
                        }
                        const replacedFormula = typeMap[key].formula.formula.replace(/\[(.*?)\]/g, (match, fieldName) => item[fieldName]);
                        let result = 0;
                        try {
                            let digit = 4;
                            if (typeMap[key].formula.type === "int") {
                                digit = 0;
                            }
                            // 使用 eval() 计算表达式
                            result = eval(replacedFormula);
                            // 检查计算结果是否为有限数值
                            if (!Number.isFinite(result)) {
                                result = 0;
                            }
                            item[key] = Number(result.toFixed(digit))
                        } catch (error) {
                            console.error(`计算公式出错：${error}`);
                        }
                    })
                })
                console.log(newData)
                this.setState({data: newData})
            } catch (e) {
                console.log(e)
            } finally {
                this.setState({loading: false})
            }

        }
        reader.readAsBinaryString(file);

    }
    downloadTemplate = () => {
        const {template} = this.state
        ZOHO.CRM.API.getOrgVariable(template).then(function (data) {
            // 组装a标签
            let elink = document.createElement("a");
            // 设置下载文件名
            elink.download = `报价明细导入模板.xlsx`;
            elink.style.display = "none";
            elink.href = data.Success.Content;
            document.body.appendChild(elink);
            elink.click();
            document.body.removeChild(elink);
            window.URL.revokeObjectURL(elink.href);
        });

    }


    render() {
        const {
            columns,
            data,
            scrollWidth,
            selectedRowKeys,
            loading,
            modalVisible,
            productData,
            productColumns,
            selectedProductRowKeys,
            screenHeight,
            template,
        } = this.state;
        return (
            <div>
                <div>
                    <Button onClick={this.addRow} loading={loading} type="primary" style={{marginRight: 10}}>
                        新增一行
                    </Button>
                    <Button onClick={this.removeRow} loading={loading} type="primary" danger
                            style={{marginRight: 10}}>删除一行</Button>
                    <Button onClick={this.handleOpenModal} loading={loading} type="primary" style={{marginRight: 10}}>
                        挑选商品
                    </Button>
                    <Link onClick={this.downloadTemplate} style={{marginRight: 10}} hidden={isBlank(template)}>
                        下载示例文件
                    </Link>
                    <Upload beforeUpload={this.importFile} accept=".xlsx,.xls" maxCount={1}>
                        <Button type="primary" loading={loading}
                                style={{marginRight: 10, display: !isBlank(template) ? 'block' : 'none'}}>
                            导入文件
                        </Button>
                    </Upload>
                </div>

                <Modal
                    open={modalVisible}
                    onCancel={this.handleCloseModal}
                    onOk={this.handleOkModal}
                    cancelText={"关闭"}
                    style={{top: 0, left: 0, right: 0, bottom: 0}}
                    width="100%"
                    okText={"确认已挑选产品"}
                    centered
                >
                    <Table
                        rowSelection={{
                            fixed: true,
                            selectedRowKeys: selectedProductRowKeys, // 多选表格选中行的 keys 数组
                            onChange: this.onProductSelectChange, // 选中行发生变化时的回调函数
                        }} columns={productColumns}
                        dataSource={productData}
                        size="small"
                        scroll={{x: 200, y: (screenHeight * 2 / 3)}}/>
                </Modal>
                <Table
                    rowSelection={{
                        fixed: true,
                        selectedRowKeys: selectedRowKeys, // 多选表格选中行的 keys 数组
                        onChange: this.onSelectChange, // 选中行发生变化时的回调函数
                    }}
                    rowClassName={() => 'custom-row'}
                    loading={loading}
                    columns={columns}
                    dataSource={data}
                    size="small"
                    pagination={false}
                    summary={(currentPageData) => {
                        let sumcolumns = [];
                        let sumData = {};
                        columns.map(item => {
                            if (item.sum === true) {
                                sumcolumns.push(item.dataIndex)
                                sumData[item.dataIndex] = 0;
                            }
                        });
                        currentPageData.forEach(item => {
                            Object.entries(item).forEach(([key, value]) => {
                                if (sumcolumns.includes(key)) {
                                    sumData[key] += value;
                                }
                            });
                        });
                        this.props.updateTotal(sumData)
                        return (
                            <>

                            </>
                        );
                    }}
                    scroll={{x: scrollWidth, y: screenHeight * 3 / 5}}/>
            </div>

        );
    }

}

export default QuoteTable;